# -*- coding: utf-8 -*-

from __future__ import with_statement

from datetime import datetime
from google.appengine.ext import db
from dicthash.for_testing import captured_templates, in_namespace
from werkzeug.urls import url_decode
from urlparse import urlparse

from lenta.code.backends.working.models import Lenta, Note
from .base import TestFunctionalBase


class BaseTest(TestFunctionalBase):
    TEMPLATES = {
        'lenta/root_logged.html': """
        """,
        'lenta/root_anonymous.html': """
        """,
        '/lenta/browse_lenta.html': """
        """,
        '/lenta/note/notes_by_tag.html': """
        """
    }
    

class TestRootPage(BaseTest):
    """
    Tests `lenta.views.root_page` view.
    """
    def test_anonymous(self):
        """ """
        self.user = None
        with captured_templates(self.app) as tmpl_info:
            res = self.test_client.get('/lenta/')
            self.assertEqual(res.status_code, 200)
            self.assertEqual(tmpl_info[0][0], "lenta/root_anonymous.html")
        
    def test_logged_no_lentas(self):
        """ """
        with captured_templates(self.app) as tmpl_info:
            res = self.test_client.get('/lenta/')
            self.assertEqual(res.status_code, 200)
            self.assertEqual(tmpl_info[0][0], "lenta/root_logged.html")
            self.assertEqual(len(tmpl_info[0][1]['my_lentas']), 0)
            
    def test_logged(self):
        """ """
        with in_namespace(self.namespace):
            Lenta.new(name="A", desc="AAA").put()
            Lenta.new(name="B", desc="BBB").put()
            
        with captured_templates(self.app) as tmpl_info:
            res = self.test_client.get('/lenta/')
            self.assertEqual(res.status_code, 200)
            self.assertEqual(tmpl_info[0][0], "lenta/root_logged.html")
            self.assertEqual(len(tmpl_info[0][1]['my_lentas']), 2)
            
            
class TestBrowseLenta(BaseTest):
    """
    Testing `lenta.views._browse_lenta` function.
    """
    def setUp(self):
        """ """
        super(TestBrowseLenta, self).setUp()
        self.dttm_list = [
                    datetime(2012, 1, 31), # 0
                    datetime(2012, 1, 30), #
                    datetime(2012, 1, 29), # 2
                    datetime(2012, 1, 28), #
                    datetime(2012, 1, 27), # 4
                    datetime(2012, 1, 26), #
                    datetime(2012, 1, 25), # 6
                    datetime(2012, 1, 24), #
                    datetime(2012, 1, 23), # 8
                    datetime(2012, 1, 22), #
                    datetime(2012, 1, 21), # 10
                    datetime(2012, 1, 20)  #
        ]
        self.namespace = 'testnamespace'
        with in_namespace(self.namespace):
            self.lenta_key = Lenta.new(name="A", desc="A B C").put()
            note_kwargs = dict(title="Boom!", twit="That's boom",
                               body="Boom-boom-boom.", parent=self.lenta_key)
            db.put([Note.new(pubDate=dttm, **note_kwargs) for dttm in self.dttm_list])
        
    def test_default_dttm(self):
        """
        Test default behavior than dttm is not provided.
        """
        with captured_templates(self.app) as tmpl_info:
            res = self.test_client.get("/lenta/%s/%s?limit=10" % (self.namespace, self.lenta_key.id()))
        
            self.assertEqual(res.status_code, 200)
            self.assertEqual(tmpl_info[0][0], "/lenta/browse_lenta.html")
            
            self.assertEqual(len([_ for _ in tmpl_info[0][1]['notes']]), 10)
            
            self.assertEqual(url_decode(urlparse(tmpl_info[0][1]['next_page_url']).query, cls=dict),
                             {'limit':'10', 'dttm':'2012-01-22-00-00-00'})
            
            
class TestGetNotesByTag(BaseTest):
    """
    Testing `lenta.views._get_notes_by_tag` function.
    """
    def setUp(self):
        """ """
        super(TestGetNotesByTag, self).setUp()
        self.dttm_list = [
                    datetime(2012, 1, 31), # 0
                    datetime(2012, 1, 30), #
                    datetime(2012, 1, 29), # 2
                    datetime(2012, 1, 28), #
                    datetime(2012, 1, 27), # 4
                    datetime(2012, 1, 26), #
                    datetime(2012, 1, 25), # 6
                    datetime(2012, 1, 24), #
                    datetime(2012, 1, 23), # 8
                    datetime(2012, 1, 22), #
                    datetime(2012, 1, 21), # 10
                    datetime(2012, 1, 20), #
                    datetime(2012, 1, 19), # 12
                    datetime(2012, 1, 18)  #
        ]
        self.tag_list = [
                    ['firebird'], # 0
                    ['firebird'], #
                    ['firebird'], # 2
                    ['sadko'],    #
                    ['firebird'], # 4
                    ['firebird'], #
                    ['firebird'], # 6
                    ['firebird'], #
                    ['mlada'],    # 8
                    ['firebird'], #
                    ['firebird'], # 10
                    ['firebird'], #
                    ['firebird'], # 12
                    ['firebird'], #
        ]
        
        self.namespace = 'testnamespace'
        with in_namespace(self.namespace):
            self.lenta_key = Lenta.new(name="A", desc="A B C").put()
            
            note_kwargs = dict(title="Boom!", twit="That's boom",
                               body="Boom-boom-boom.", parent=self.lenta_key)
            
            db.put([Note.new(pubDate=dttm, tags=tags, **note_kwargs)
                    for dttm, tags in zip(self.dttm_list, self.tag_list)])
            
    def test_setup(self):
        """ """
        self.assertEqual(len(Note.all(namespace=self.namespace).fetch(100)), 14)
        self.assertEqual(len(Note.all(namespace=self.namespace).filter('tags =', 'firebird').fetch(100)), 12)
        self.assertEqual(len(Note.all(namespace=self.namespace).filter('tags =', 'sadko').fetch(100)), 1)
        self.assertEqual(len(Note.all(namespace=self.namespace).filter('tags =', 'mlada').fetch(100)), 1)     
            
    def test_default_dttm(self):
        """
        Test default behavior than dttm is not provided.
        """
        with captured_templates(self.app) as tmpl_info:
            res = self.test_client.get("/lenta/%s/%s/note/tag/%s?limit=10" % \
                                                (self.namespace, self.lenta_key.id(), 'firebird'))
         
            self.assertEqual(res.status_code, 200)
            self.assertEqual(tmpl_info[0][0], "/lenta/note/notes_by_tag.html")
            self.assertEqual(len([_ for _ in tmpl_info[0][1]['notes']]), 10)
            
            self.assertEqual(url_decode(urlparse(tmpl_info[0][1]['next_page_url']).query, cls=dict),
                             {'limit':'10', 'dttm':'2012-01-20-00-00-00'})